package net.javacloud.service;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.iqregister.AccountManager;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Crowhyc on 2016/6/24.
 */
public class AccountRegister {
    private static AbstractXMPPConnection connection;
    private final static String host = Tester.host;
    private final static int port = 5222;

    static {
        XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder().setCompressionEnabled(true).setUsernameAndPassword(Tester.adminName, Tester.adminPwd).setServiceName(host).setHost(host).setPort(port).setSecurityMode(XMPPTCPConnectionConfiguration.SecurityMode.disabled).setDebuggerEnabled(false).build();

        /** 创建connection链接 */
        /** 建立连接 */
        connection = new XMPPTCPConnection(config);
        try {
            connection.connect().login();
        } catch (XMPPException | SmackException | IOException e) {
            e.printStackTrace();
        }
    }

    public static AbstractXMPPConnection getConnection() {
        return connection;
    }

    public static boolean userRegister(String username, String password) {
        if (connection != null) {
            AccountManager accountManager = AccountManager.getInstance(connection);
            accountManager.sensitiveOperationOverInsecureConnection(true);
            try {
                if (accountManager.supportsAccountCreation()) {
                    Map<String, String> map = new HashMap();
                    accountManager.createAccount(username, password, map);
                }
            } catch (SmackException.NoResponseException | XMPPException.XMPPErrorException | SmackException.NotConnectedException e) {
                e.printStackTrace();
            }
            System.out.println(username + "用户注册成功");
            return true;
        }
        return false;
    }

    public static boolean delUser(XMPPTCPConnection conn) throws SmackException.NotConnectedException, XMPPException.XMPPErrorException, SmackException.NoResponseException {
        try {
            AccountManager accountManager = AccountManager.getInstance(conn);
            accountManager.deleteAccount();
        } catch (Exception e) {
            System.out.println(conn.getUser() + "删除失败");
            e.printStackTrace();
            return false;
        }
        return true;
    }

}
